#include "FFmpegDemuxer.h"
#include <libavutil/time.h>

int FFmpegDemuxer::decode_interrupt_cb(void *ctx)
{
    FFmpegDemuxer *pThis = (FFmpegDemuxer *)ctx;

    if (pThis->isConnected)
    {
        int64_t nDurTime = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - pThis->m_nStartOpenTS).count();
        if (nDurTime > 5 * 1000)
            return -1;

        return 0;
    }
    else
    {
        int64_t nDurTime = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - pThis->m_nStartOpenTS).count();
        if (nDurTime > 5 * 1000)
        {
            return 1;
        }

        return 0;
    }
}

AVFormatContext *FFmpegDemuxer::CreateFormatContext(const char *szFilePath)
{
    avformat_network_init();

    AVDictionary *options = nullptr;
    av_dict_set(&options, "rtsp_transport", "tcp", 0);
    // av_dict_set(&options, "stimeout ", "5000000", 0);

    // AVFormatContext *ctx = NULL;
    AVFormatContext *ctx = avformat_alloc_context();
    ctx->interrupt_callback.callback = decode_interrupt_cb;
    ctx->interrupt_callback.opaque = (void *)this;
    m_nStartOpenTS = std::chrono::system_clock::now();
    isConnected = false;

    //ctx->probesize = 10000000;
    //ctx->flags |= AVFMT_FLAG_NOBUFFER;
    //ctx->max_analyze_duration = 5 * AV_TIME_BASE;

    // ck(avformat_open_input(&ctx, szFilePath, NULL, &options));
    int ret = avformat_open_input(&ctx, szFilePath, NULL, &options);
    return ctx;
}